package org.jeecg.modules.hqbaoxiao.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.hqbaoxiao.entity.HqBaoxiao;
import org.jeecg.modules.hqbaoxiao.entity.HqBaoxiaoDetail;
import org.jeecg.modules.hqbaoxiao.service.IHqBaoxiaoDetailService;
import org.jeecg.modules.hqbaoxiao.service.IHqBaoxiaoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.model.TreeSelectModel;
import org.jeecg.modules.workflow.utils.ProcessKit;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 报销
 * @Author: jeecg-boot
 * @Date:   2020-07-07
 * @Version: V1.0
 */
@Api(tags="报销")
@RestController
@RequestMapping("/hqbaoxiao/hqBaoxiao")
@Slf4j
public class HqBaoxiaoController extends JeecgController<HqBaoxiao, IHqBaoxiaoService> {
	@Autowired
	private IHqBaoxiaoService hqBaoxiaoService;
	 @Autowired
	 private IHqBaoxiaoDetailService hqBaoxiaoDetailService;
	/**
	 * 分页列表查询
	 *
	 * @param hqBaoxiao
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "报销-分页列表查询")
	@ApiOperation(value="报销-分页列表查询", notes="报销-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HqBaoxiao hqBaoxiao,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HqBaoxiao> queryWrapper = QueryGenerator.initQueryWrapper(hqBaoxiao, req.getParameterMap());
		Page<HqBaoxiao> page = new Page<HqBaoxiao>(pageNo, pageSize);
		IPage<HqBaoxiao> pageList = hqBaoxiaoService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param hqBaoxiao
	 * @return
	 */
	@AutoLog(value = "报销-添加")
	@ApiOperation(value="报销-添加", notes="报销-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody HqBaoxiao hqBaoxiao) {
	 if (hqBaoxiao.getDjlx().equals("chailv")) {
		if(hqBaoxiao.getDddd().length()>60){
		return 	Result.error("到达地点不得超过60个字符，请重新输入");
		}
		if(hqBaoxiao.getMemo().length()>60){
			return 	Result.error("备注不得超过60个字符，请重新输入");
		}
		if(hqBaoxiao.getBzb().length()>60){
			return 	Result.error("部职别不得超过60个字符，请重新输入");
		}
        for (int i=0;i<hqBaoxiao.getHqBaoxiaoDetailList().size();i++){
        	List<HqBaoxiaoDetail> hqBaoxiaoDetail=hqBaoxiao.getHqBaoxiaoDetailList();
        	if (hqBaoxiaoDetail.get(i).getKznr().length()>60){
				return 	Result.error("开支内容不得超过60个字符，请重新输入");
			}
			if (hqBaoxiaoDetail.get(i).getShoukr().length()>60){
				return 	Result.error("收款人不得超过60个字符，请重新输入");
			}
			if (hqBaoxiaoDetail.get(i).getZhuanzje().length()>60){
				return 	Result.error("转账金额不得超过60个字符，请重新输入");
			}
		 }
		}
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		hqBaoxiaoService.startFlow(hqBaoxiao,user);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param hqBaoxiao
	 * @return
	 */
	@AutoLog(value = "报销-编辑")
	@ApiOperation(value="报销-编辑", notes="报销-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody HqBaoxiao hqBaoxiao) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		hqBaoxiaoService.applyAgain(hqBaoxiao,user);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "报销-通过id删除")
	@ApiOperation(value="报销-通过id删除", notes="报销-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		hqBaoxiaoService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "报销-批量删除")
	@ApiOperation(value="报销-批量删除", notes="报销-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.hqBaoxiaoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "报销-通过id查询")
	@ApiOperation(value="报销-通过id查询", notes="报销-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		HqBaoxiao hqBaoxiao = hqBaoxiaoService.getById(id);
		if(hqBaoxiao==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(hqBaoxiao);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hqBaoxiao
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HqBaoxiao hqBaoxiao) {
        return super.exportXls(request, hqBaoxiao, HqBaoxiao.class, "报销");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HqBaoxiao.class);
    }


	 @AutoLog(value = "我的申请-分页列表查询")
	 @ApiOperation(value="我的申请-分页列表查询", notes="我的申请-分页列表查询")
	 @GetMapping(value = "/myapplylist")
	 public Result<?> myApplyList(HqBaoxiao hqBaoxiao,
								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								  HttpServletRequest req) {

		 Page<HqBaoxiao> page = new Page<>(pageNo, pageSize);
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 IPage<HqBaoxiao> iPage = hqBaoxiaoService.myApplyList(page,user,hqBaoxiao);
		 if(iPage.getTotal()>0){
			 iPage.getRecords().forEach(record->{
				 if(null != record.getEndTime()){
					 record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
				 }else {
					 if (null != record.getAuditStatus()) {
						 record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
					 }else{
						 record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
					 }
				 }
			 });
		 }
		 return Result.ok(iPage);
	 }

	 @AutoLog(value = "我的待办-分页列表查询")
	 @ApiOperation(value="我的待办-分页列表查询", notes="我的待办-分页列表查询")
	 @GetMapping(value = "/mytodolist")
	 public Result<?> myTodoList(HqBaoxiao hqBaoxiao,
								 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								 HttpServletRequest req) {
		 Page<HqBaoxiao> page = new Page<>(pageNo, pageSize);
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 IPage<HqBaoxiao> iPage = hqBaoxiaoService.myTodoTasks(page,user,hqBaoxiao);
		 return Result.ok(iPage);
	 }

	 @AutoLog(value = "我的已办-分页列表查询")
	 @ApiOperation(value="我的已办-分页列表查询", notes="我的已办-分页列表查询")
	 @GetMapping(value = "/mydonelist")
	 public Result<?> myDoneList(HqBaoxiao hqBaoxiao,
								 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								 HttpServletRequest req) {
		 Page<HqBaoxiao> page = new Page<>(pageNo, pageSize);
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 IPage<HqBaoxiao> iPage = hqBaoxiaoService.myDoneTasks(page,user,hqBaoxiao);
		 if(iPage.getTotal()>0){
			 iPage.getRecords().forEach(record->{
				 if(null != record.getEndTime()){
					 record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
				 }else {
					 record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
				 }
			 });
		 }
		 return Result.ok(page);
	 }

	 @AutoLog(value = "任务审批")
	 @ApiOperation(value="任务审批", notes="任务审批")
	 @PostMapping(value = "/completetask")
	 public Result<?> completeTask(@RequestBody Map params) {
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 hqBaoxiaoService.complateTask(loginUser, (String)params.get("hezje"), (String)params.get("taskId"),(String)params.get("processInstanceId"), (Integer) params.get("auditStatus"), (String)params.get("auditMemo"));

		 return Result.ok("操作成功");
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "hq_baoxiao_detail通过主表ID查询")
	 @ApiOperation(value="hq_baoxiao_detail主表ID查询", notes="hq_baoxiao_detail-通主表ID查询")
	 @GetMapping(value = "/queryHqBaoxiaoDetailByMainId")
	 public Result<?> queryHqBaoxiaoDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<HqBaoxiaoDetail> hqBaoxiaoDetailList = hqBaoxiaoDetailService.selectByMainId(id);
		 return Result.ok(hqBaoxiaoDetailList);
	 }

	 /**
	  * 加载一级节点/如果是同步 则所有数据
	  */
	 @RequestMapping(value = "/kemutree", method = RequestMethod.GET)
	 public Result<List<TreeSelectModel>> kemutree( @RequestParam(name="pid") String pid) {
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 Result<List<TreeSelectModel>> result = new Result<List<TreeSelectModel>>();
		 try {
			 List<TreeSelectModel> ls = this.hqBaoxiaoService.kemulistByPid(loginUser.getOrgCode(), pid);
			 loadAllCategoryChildren(loginUser.getOrgCode(),ls);
			 result.setResult(ls);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.setMessage(e.getMessage());
			 result.setSuccess(false);
		 }
		 return result;
	 }

	 /**
	  * 递归求子节点 同步加载用到
	  */
	 private void loadAllCategoryChildren(String orgCode,List<TreeSelectModel> ls) {
		 for (TreeSelectModel tsm : ls) {
			 List<TreeSelectModel> temp = this.hqBaoxiaoService.kemulistByPid(orgCode,tsm.getKey());
			 if(temp!=null && temp.size()>0) {
				 tsm.setChildren(temp);
				 loadAllCategoryChildren(orgCode,temp);
			 }
		 }
	 }
}
